package vigo_tool

import (
	"flag"
	"github.com/garyburd/redigo/redis"
	"gitlab.gaodun.com/golib/gderror"
	"time"
	"permission/config"
	"permission/vigo_loger"
)

var (
	pool          *redis.Pool
	redisServer   *string
	redisPassword *string
)

var RedisPool, _ = GetRedisPool()

func NewPool(server, password string) (*redis.Pool, error) {
	return &redis.Pool{
		MaxIdle:     500,
		MaxActive:   4000,
		IdleTimeout: 30 * time.Second,
		Wait:        true,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", server)
			if err != nil {
				return nil, err
			}
			if password != "" {
				if _, err := c.Do("AUTH", password); err != nil {
					c.Close()
					return nil, err
				}
			}
			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			if time.Since(t) < time.Minute {
				return nil
			}
			_, err := c.Do("PING")
			return err
		},
	}, nil
}

func GetRedisPool() (*redis.Pool, error) {
	var UcConfig, err = config.InitConfig()
	if err != nil {
		return nil, err
	}
	redisServer = flag.String("redisServer", UcConfig["VIGO_REDIS_HOST"]+":"+UcConfig["VIGO_REDIS_PORT"], "")
	redisPassword = flag.String("redisPassword", UcConfig["VIGO_REDIS_AUTH"], "")
	flag.Parse()
	pool, err = NewPool(*redisServer, *redisPassword)
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
		return nil, err
	}
	return pool, nil
}
